package xcmg.device;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
@Slf4j
public class RedissonConfig {

    private static final String REDIS_PROTOCOL = "redis://";

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private String port;
    @Value("${spring.redis.password:#{null}}")
    private String password;

    @Value("${spring.redis.database:0}")
    private int database;

    // 初始化检查，防止配置缺失
    @PostConstruct
    public void initCheck() {
        if (host == null || host.trim().isEmpty()) {
            throw new IllegalArgumentException("Redis host configuration is missing.");
        }
        if (port == null || port.trim().isEmpty()) {
            throw new IllegalArgumentException("Redis port configuration is missing.");
        }
    }

    @Bean(destroyMethod = "shutdown")
    public RedissonClient getRedisson() throws Exception {
        Config config = buildRedissonConfig();
        RedissonClient redisson = Redisson.create(config);

        // 避免打印敏感信息
        log.info("redisson initialized with host: {}, port: {}, database: {}", host, port, database);
        return redisson;
    }

    private Config buildRedissonConfig() {
        Config config = new Config();
        String address = REDIS_PROTOCOL + host + ":" + port;
        config.useSingleServer()
                .setAddress(address)
                .setPassword(password)
                .setDatabase(database);
        return config;
    }
}
